package com.ktjiaoyu.service.impl;

import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.mapper.SupplierMapper;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.utils.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("supplierService")
public class SupplierServiceImpl implements SupplierService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SupplierServiceImpl.class);

    @Autowired
    private SupplierMapper supplierMapper;

    // 提供setter方法用于注入属性
    public void setSupplierMapper(SupplierMapper supplierMapper) {
        this.supplierMapper = supplierMapper;
    }

    @Override
    public Supplier getBySupCode(String supCode) {
        return supplierMapper.getBySupCode(supCode);
    }

    @Override
    public Boolean delete(Integer id) {
        return supplierMapper.delete(id);
    }

    @Override
    public Page<Supplier> findPage(Supplier entity, Integer pageNo, Integer pageSize) throws Exception {
        Page<Supplier> page = null;
        try {
            page = new Page<Supplier>();
            page.setPageSize(pageSize);
            //查询总数,计算总页数
            Long count = supplierMapper.count(entity);
            page.setTotalCount(count.intValue());
            page.setPageNo(pageNo);
            //查询分页数据
            List<Supplier> data = supplierMapper.getPage(entity,page.offset(),page.getPageSize());
            page.setData(data);
        }catch (Exception e){
            LOGGER.error("执行supplierServiceImpl.findPage(Supplier,Integer,Integer)方法出现异常",e);
        }
        return page;
    }


    @Override
    public boolean saveOrUpdate(Supplier entity) throws Exception {
        try {
            if(entity.getId() == null){
                //无主键时新增
                return supplierMapper.insert(entity)>0;
            }else {
                //有主键时修改
                return supplierMapper.update(entity)>0;
            }
        }catch (Exception e){
            LOGGER.error("执行supplierServiceImpl.saveOrUpdate(supplier)方法出现异常",e);
            throw e;
        }
    }

    @Override
    public Supplier findById(Long id) throws Exception {
        try {
            return supplierMapper.getById(id);
        }catch (Exception e){
            LOGGER.error("执行SupplierServiceImpl.findById(Long)方法出现异常",e);
            throw e;
        }
    }

    @Override
    public List<Supplier> findAll() throws Exception {
        try {
            return supplierMapper.getAll();
        }catch (Exception e){
            LOGGER.error("执行SysRoleServiceImpl.findAll()方法出现异常",e);
            throw e;
        }
    }
}
